package org.erepublik.company.service;

import java.io.File;
import java.io.FileInputStream;
import java.net.MalformedURLException;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;

import org.erepublik.company.Configuration;
import org.erepublik.company.ECountry;
import org.erepublik.company.thread.ProductUpdater;
import org.erepublik.company.utils.Utils;
import org.json.JSONObject;

/**
 * Servis odczytujacy aktualny plikow z JSONa zapisanego na dysku.
 * 
 * Obiekt na biezaco sprawdza, czy nie ma pliku z bardziej aktualnymi danymi
 *
 * @author Kacper Gorski 'Railman' railman85@gmail.com
 */
public class JSONExchangeRateService implements IExchangeRateService {

    // folder, w ktorym znajduja sie jsopny
	public static String databasePath = Configuration.databasePath + "/currency";
	private long scannTime;
	private HashMap<ECountry, Double> exchangeRates;

	public JSONExchangeRateService() {
		readExchangeRatesFromFile();
	}
	
	public void update() {
		long newScannTime = ProductUpdater.getLastScanTime("currency");
		if (newScannTime>scannTime)
			readExchangeRatesFromFile();
	}

	private void readExchangeRatesFromFile() {
		String urlToFile = getLastProductFile();
		try {
			scannTime = ProductUpdater.getLastScanTime("currency");
			String jsonAsString = Utils.convertStreamToString( new FileInputStream( new File(urlToFile) ) );
			JSONObject json = new JSONObject(jsonAsString);
			HashMap<ECountry, Double> map = new HashMap<ECountry, Double>();
			ECountry[] countries = ECountry.values();
			for (ECountry country : countries) {
				Object obj = json.get(country.toString());
				Double value = 0.0d;
				if (obj instanceof Integer)
					value = ((Integer)obj).doubleValue() ;
				else
					value = (Double)obj;
				map.put(country, value);
			}
			exchangeRates = map;
			
		} catch(Exception e) {
			e.printStackTrace();
		}
	}

	public HashMap<ECountry, Double> getExchangeRates() throws Exception {
		update();
		return exchangeRates;
	}



    private static void createDatabaseFolderIfNotExists() {
        File file_main = new File(Configuration.databasePath);
        file_main.mkdir();
        File file_sub = new File(databasePath);
        file_sub.mkdir();
    }
	
	public static String getLastProductFile() {

	    createDatabaseFolderIfNotExists();
	    
		URL urlToDirectory = null;
		try {
			urlToDirectory = new URL("file://" + databasePath);
		} catch (MalformedURLException e1) {
			e1.printStackTrace();
		}

		try {
			File fildirectory = new File(urlToDirectory.toURI());
			File[] files = fildirectory.listFiles();
			ArrayList<String> fileList = new ArrayList<String>();
			for (File file : files) {
				if (file.getPath().endsWith("-currency.json"))
					fileList.add(file.getName());
			}
			String[] fileTable = fileList.toArray(new String[0]);
			Arrays.sort(fileTable);
			return databasePath + "/" + fileTable[fileTable.length - 1];
		} catch (URISyntaxException e) {
			e.printStackTrace();
		}
		return null;
	}

}
